package com.jblv.frame.common.fastdfs.image;

import com.jblv.frame.common.utils.UUIDGenerator;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.*;
import java.util.Iterator;
import java.util.List;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title ImageUtils
 * @projectName jblv-frame
 * @packageName com.jblv.common.fastdfs.image
 * @description ImageUtils
 * @date Create at 2020/5/7 11:01
 * @since jdk1.8
 */


public class ImageUtils {
    private static Logger logger = LoggerFactory.getLogger(ImageUtils.class);
    public static final int DEFAULT_VALUE = 10000;

    public ImageUtils() {
    }

    public static boolean zoomWidthConstrain(InputStream inputStream, int width, int height, OutputStream outputStream) {
        try {
            Thumbnails.of(new InputStream[]{inputStream}).outputQuality(1.0D).size(width, height).toOutputStream(outputStream);
            return true;
        } catch (IOException var5) {
            var5.printStackTrace();
            return false;
        }
    }

    public static boolean zoom(InputStream inputStream, int width, int height, OutputStream outputStream) {

        if (null != inputStream && null != outputStream) {
            File zoomFile = null;

            boolean var7;
            try {
                if (width > 0 && height > 0) {
                    BufferedImage sourceImg = ImageIO.read(inputStream);
                    float widthScal = 1.0F;
                    float heightScal = 1.0F;
                    float maxScal = 1.0F;
                    int sourceImgWidth = sourceImg.getWidth();
                    int sourceImgHeght = sourceImg.getHeight();
                    widthScal = (float)((double)width / ((double)sourceImgWidth + 0.0D));
                    heightScal = (float)((double)height / ((double)sourceImgHeght + 0.0D));
                    if (widthScal > heightScal) {
                        maxScal = widthScal;
                    } else {
                        maxScal = heightScal;
                    }

                    int scalImageWith = (int)(maxScal * (float)sourceImgWidth);
                    int scalImageHeight = (int)(maxScal * (float)sourceImgHeght);
                    int x = (scalImageWith - width) / 2;
                    int y = (scalImageHeight - height) / 2;
                    zoomFile = File.createTempFile("zoom", ".png");
                    Thumbnails.of(new BufferedImage[]{sourceImg}).scale((double)maxScal).outputQuality(1.0D).toFile(zoomFile);
                    Thumbnails.of(new File[]{zoomFile}).sourceRegion(x, y, width, height).outputQuality(1.0D).size(width, height).keepAspectRatio(true).toOutputStream(outputStream);
                    sourceImg = null;
                    return true;
                }

                var7 = false;
            } catch (IOException var24) {
                logger.error("文件压缩失败！");
                boolean var8 = false;
                return var8;
            } finally {
                if (zoomFile != null) {
                    zoomFile.delete();
                }

                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException var23) {
                    var23.printStackTrace();
                }

            }

            return var7;
        } else {
            return false;
        }
    }

    public static boolean cut(String fromImagePath, int x, int y, int width, int height, String toImagePath) throws Exception {
        if (width > 0 && height > 0) {
            try {
                Thumbnails.of(new String[]{fromImagePath}).sourceRegion(x, y, width, height).outputQuality(1.0D).size(width, height).keepAspectRatio(false).toFile(toImagePath);
                return true;
            } catch (IOException var7) {
                var7.printStackTrace();
                throw new Exception(var7);
            }
        } else {
            return false;
        }
    }

    public static boolean cut(InputStream inputStream, int x, int y, int width, int height, OutputStream outputStream) {
        if (null != inputStream && null != outputStream) {
            if (width > 0 && height > 0) {
                File tempFile = null;

                try {
                    tempFile = File.createTempFile("temp", (String)null);
                } catch (IOException var26) {
                    var26.printStackTrace();
                }

                inputstreamtofile(inputStream, tempFile);
                BufferedImage sourceImg = null;

                try {
                    sourceImg = ImageIO.read(tempFile);
                } catch (IOException var25) {
                    var25.printStackTrace();
                }

                float widthScal = 1.0F;
                float heightScal = 1.0F;
                float maxScal = 1.0F;
                if (x + width > sourceImg.getWidth()) {
                    widthScal = (float)((double)width / ((double)sourceImg.getWidth() + 0.0D));
                }

                if (y + height > sourceImg.getHeight()) {
                    heightScal = (float)((double)height / ((double)sourceImg.getHeight() + 0.0D));
                }

                if (widthScal > heightScal) {
                    maxScal = widthScal;
                } else {
                    maxScal = heightScal;
                }

                File zoomFile = null;

                try {
                    if (maxScal > 1.0F) {
                        zoomFile = File.createTempFile("zoom", ".png");
                        Thumbnails.of(new File[]{tempFile}).scale((double)maxScal).outputQuality(1.0D).toFile(zoomFile);
                        Thumbnails.of(new File[]{zoomFile}).sourceRegion(x, y, width, height).outputQuality(1.0D).size(width, height).keepAspectRatio(true).toOutputStream(outputStream);
                    } else {
                        Thumbnails.of(new File[]{tempFile}).sourceRegion(x, y, width, height).outputQuality(1.0D).size(width, height).keepAspectRatio(true).toOutputStream(outputStream);
                    }

                    sourceImg = null;
                } catch (IOException var23) {
                    var23.printStackTrace();
                } finally {
                    try {
                        outputStream.flush();
                        outputStream.close();
                    } catch (IOException var22) {
                        var22.printStackTrace();
                    }

                    if (zoomFile != null) {
                        zoomFile.delete();
                    }

                    if (tempFile != null) {
                        tempFile.delete();
                    }

                }

                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static void pressText(String pressText, File srcFile, String fontName, int fontStyle, int color, int fontSize, int x, int y) {
        try {
            Image src = ImageIO.read(srcFile);
            int width = src.getWidth((ImageObserver)null);
            int height = src.getHeight((ImageObserver)null);
            BufferedImage image = new BufferedImage(width, height, 1);
            Graphics g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, (ImageObserver)null);
            g.setColor(new Color(color, false));
            g.setFont(new Font(fontName, fontStyle, fontSize));
            width = width - fontSize * pressText.length() / 2 - x;
            height = height - fontSize / 2 - y;
            g.drawString(pressText, width, height);
            g.dispose();
            saveImageUsingJPGWithQuality(image, srcFile, 1.0F);
        } catch (Exception var13) {
            System.out.println(var13);
        }

    }

    public static void inputstreamtofile(InputStream ins, File file) {
        FileOutputStream os = null;

        try {
            os = new FileOutputStream(file);
            byte[] buffer = new byte[8192];
            int bytesRead;
            while((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException var15) {
            var15.printStackTrace();
        } catch (IOException var16) {
            var16.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                os = null;
            }

        }

    }

    public static void saveImageUsingJPGWithQuality(BufferedImage image, File file, float quality) throws Exception {
        BufferedImage newBufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), 5);
        newBufferedImage.getGraphics().drawImage(image, 0, 0, (ImageObserver)null);
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
        ImageWriter imageWriter = (ImageWriter)iter.next();
        ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
        iwp.setCompressionMode(2);
        iwp.setCompressionQuality(quality);
        FileImageOutputStream fileImageOutput = new FileImageOutputStream(file);
        imageWriter.setOutput(fileImageOutput);
        IIOImage iio_image = new IIOImage(newBufferedImage, (List)null, (IIOMetadata)null);
        imageWriter.write((IIOMetadata)null, iio_image, iwp);
        imageWriter.dispose();
    }

    public static void watermark(File srcFile, String text) {
        pressText(text, srcFile, "宋体", 0, 0, 12, 10, 10);
        pressText(text, srcFile, "宋体", 0, 16777215, 12, 11, 11);
    }

    public static File cut(InputStream is, String fileExtName, PicSize picSize) {
        File tempFile = null;
        String prefix = UUIDGenerator.getUUID();
        String suffix = getFileNameExt(fileExtName);
        FileOutputStream outputStream = null;

        try {
            tempFile = File.createTempFile(prefix, suffix);
            outputStream = new FileOutputStream(tempFile);
            int width;
            int height;
            if (picSize.getHeight() == 0) {
                width = picSize.getWidth();
                height = 10000;
            } else if (picSize.getWidth() == 0) {
                width = 10000;
                height = picSize.getHeight();
            } else {
                width = picSize.getWidth();
                height = picSize.getHeight();
            }

            zoom(is, width, height, outputStream);
        } catch (FileNotFoundException var19) {
            var19.printStackTrace();
        } catch (IOException var20) {
            var20.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException var18) {
                    var18.printStackTrace();
                }
            }

        }

        return tempFile;
    }

    private static String getFileNameExt(String fileName) {
        String ext = "";
        if (StringUtils.isNotEmpty(fileName.trim())) {
            int index = fileName.lastIndexOf(".");
            if (index > -1) {
                ext = fileName.substring(index);
            }
        }

        return ext;
    }

    public static void main(String[] args) {
        try {
            FileInputStream in = new FileInputStream("D:/1.jpg");
            FileOutputStream out = new FileOutputStream("D:/2018.jpg");
            zoom(in, 400, 400, out);
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        try {
            cut((String)"D:/1.jpg", 3, 6, 100, 100, (String)"D:/720.jpg");
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        watermark(new File("D:/1.jpg"), "杨小二工作室-给图片添加水印测试");
    }
}

